// pages/address_list/index.js
Page({
  data: {
    navBarHeight: 0,
    contentTop: 0,
    bottomSafeArea: 0,
    
    // 页面模式：select(选择模式) 或 manage(管理模式)
    pageMode: 'manage',
    
    // 地址列表
    addressList: [],
    
    // 选中的地址ID（选择模式下使用）
    selectedAddressId: '',
    
    // 加载状态
    loading: true,
    
    // 空状态
    isEmpty: false
  },

  onLoad(options) {
    // 计算导航栏高度和底部安全区域
    const systemInfo = wx.getSystemInfoSync()
    const statusBarHeight = systemInfo.statusBarHeight
    const navBarHeight = statusBarHeight + 44
    const bottomSafeArea = systemInfo.safeArea ? systemInfo.screenHeight - systemInfo.safeArea.bottom : 0
    
    this.setData({
      navBarHeight,
      contentTop: navBarHeight,
      bottomSafeArea
    })
    
    // 判断页面模式
    const mode = options.mode || 'manage'
    const selectedId = options.selectedId || ''
    
    this.setData({
      pageMode: mode,
      selectedAddressId: selectedId
    })
    
    // 设置导航栏标题
    wx.setNavigationBarTitle({
      title: mode === 'select' ? '选择收货地址' : '收货地址'
    })
    
    // 加载地址列表
    this.loadAddressList()
  },

  onShow() {
    // 页面显示时重新加载地址列表
    this.loadAddressList()
  },

  // 加载地址列表
  async loadAddressList() {
    try {
      this.setData({ loading: true })
      
      const result = await wx.cloud.callFunction({
        name: 'getAddressList'
      })
      
      if (result.result.success) {
        const addressList = result.result.data || []
        this.setData({
          addressList,
          isEmpty: addressList.length === 0,
          loading: false
        })
      } else {
        throw new Error(result.result.message || '获取地址列表失败')
      }
    } catch (error) {
      console.error('加载地址列表失败:', error)
      this.setData({ loading: false })
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    }
  },

  // 选择地址（选择模式下）
  selectAddress(e) {
    if (this.data.pageMode !== 'select') return
    
    const addressId = e.currentTarget.dataset.id
    const address = this.data.addressList.find(item => item._id === addressId)
    
    if (address) {
      // 返回到订单创建页面并传递选中的地址
      const pages = getCurrentPages()
      const prevPage = pages[pages.length - 2]
      
      if (prevPage) {
        prevPage.setData({
          selectedAddress: address
        })
      }
      
      wx.navigateBack()
    }
  },

  // 设为默认地址
  async setDefaultAddress(e) {
    const addressId = e.currentTarget.dataset.id
    
    try {
      wx.showLoading({
        title: '设置中...',
        mask: true
      })
      
      const result = await wx.cloud.callFunction({
        name: 'setDefaultAddress',
        data: { addressId }
      })
      
      if (result.result.success) {
        wx.hideLoading()
        wx.showToast({
          title: '设置成功',
          icon: 'success'
        })
        
        // 更新本地缓存
        const address = this.data.addressList.find(item => item._id === addressId)
        if (address) {
          wx.setStorageSync('defaultAddress', address)
          wx.setStorageSync('addressCacheTime', Date.now())
        }
        
        // 重新加载地址列表
        this.loadAddressList()
      } else {
        throw new Error(result.result.message || '设置失败')
      }
    } catch (error) {
      console.error('设置默认地址失败:', error)
      wx.hideLoading()
      wx.showToast({
        title: error.message || '设置失败',
        icon: 'none'
      })
    }
  },

  // 编辑地址
  editAddress(e) {
    const addressId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/address_edit/index?id=${addressId}`
    })
  },

  // 删除地址
  deleteAddress(e) {
    const addressId = e.currentTarget.dataset.id
    const address = this.data.addressList.find(item => item._id === addressId)
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除${address.receiver}的收货地址吗？`,
      success: async (res) => {
        if (res.confirm) {
          try {
            wx.showLoading({
              title: '删除中...',
              mask: true
            })
            
            const result = await wx.cloud.callFunction({
              name: 'deleteAddress',
              data: { addressId }
            })
            
            if (result.result.success) {
              wx.hideLoading()
              wx.showToast({
                title: '删除成功',
                icon: 'success'
              })
              
              // 重新加载地址列表
              this.loadAddressList()
            } else {
              throw new Error(result.result.message || '删除失败')
            }
          } catch (error) {
            console.error('删除地址失败:', error)
            wx.hideLoading()
            wx.showToast({
              title: error.message || '删除失败',
              icon: 'none'
            })
          }
        }
      }
    })
  },

  // 新增地址
  addAddress() {
    wx.navigateTo({
      url: '/pages/address_edit/index'
    })
  },

  // 返回按钮
  handleBack() {
    wx.navigateBack()
  }
})